<template>
  <el-menu
    class="el-menu-vertical-demo"
    :defaultActive="defaultActive"
    :router="router"
  >
    <template v-for="(item, index) in data" :key="index">
      <el-menu-item
        v-if="!item[children] || item[children].length == 0"
        :index="item[props.index]"
        @click="onClick(item[props.index])"
      >
        <component
          v-if="item[icon]"
          class="menu-icon-svg"
          :is="`el-icon-${toLine(item[icon])}`"
        ></component>
        <span>{{ item[name] }} </span>
      </el-menu-item>
      <el-sub-menu
        v-if="item[children] && item[children].length"
        :index="item[index]"
      >
        <template #title>
          <component
            class="menu-icon-svg"
            v-if="item[icon]"
            :is="`el-icon-${toLine(item[icon])}`"
          ></component>
          <span>{{ item[name] }}</span>
        </template>
        <el-menu-item
          v-for="(subItem, subIndex) in item[children]"
          :key="subIndex"
          :index="subItem[props.index]"
          @click="onClick(subItem[props.index])"
        >
          <component
            class="menu-icon-svg"
            v-if="subItem[icon]"
            :is="`el-icon-${toLine(subItem[icon])}`"
          ></component>
          <span>{{ subItem[name] }}</span>
        </el-menu-item>
      </el-sub-menu>
    </template>
  </el-menu>
</template>

<script setup lang="ts">
import { PropType } from "vue";
import { MenuItem } from "./types.ts";
import { toLine } from "../../../utils/index.ts";
import { useRouter } from "vue-router";

const props = defineProps({
  // 菜单的数据
  data: {
    type: Array as PropType<MenuItem[]>,
    default: () => [],
  },
  // 默认高亮的菜单
  defaultActive: {
    type: String,
    default: "",
  },
  // 是否启用 vue-router 模式。 启用该模式会在激活导航时以 index 作为 path 进行路由跳转 使用 default-active 来设置加载时的激活项。
  router: {
    type: Boolean,
    default: false,
  }, // 菜单标题的键名
  name: {
    type: String,
    default: "name",
  },
  // 菜单标识的键名
  index: {
    type: String,
    default: "index",
  },
  // 菜单图标的键名
  icon: {
    type: String,
    default: "icon",
  },
  // 菜单子菜单的键名
  children: {
    type: String,
    default: "children",
  },
});
let UseRouter = useRouter();
function onClick(path: string) {
  UseRouter.push(path);
}
</script>

<style lang="scss" scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
</style>
